package com.jy.modules.cims.settle.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.balance.SettleUtilsService;
import com.jy.modules.cims.component.sysAssist.BatchService;
import com.jy.modules.cims.data.common.dto.TCMmCreditDealDetailDTO;
import com.jy.modules.cims.data.dao.CreditDealDetailDao;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.DealDto;
import com.jy.modules.cims.data.dto.balance.AssistDealDto;
import com.jy.modules.cims.data.dto.credit.CostAffiliationResultDto;
import com.jy.modules.cims.data.dto.credit.PublicSettleParamDto;
import com.jy.modules.cims.data.dto.credit.PublicSettleResultDto;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.platform.api.org.SessionAPI;
/**
 * 结算平衡
 * ClassName: SettleBalanceService 
 * @Description: TODO
 * @author dell
 * @date 2016-4-15
 */
@Service("com.jy.modules.cims.settle.service.SettleBalanceService")
public class SettleBalanceService {

	private static final Logger logger = LoggerFactory.getLogger(SettleBalanceService.class);
	
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
	public ICInteract iCInteract;
	
	@Autowired
	private CreditDealDetailDao creditDealDetailDao;
	
	

	@Autowired
    @Qualifier("com.jy.modules.cims.component.balance.SettleUtilsService")
    private SettleUtilsService settleUtilsService;
	
	@Autowired
	private SessionAPI sessionAPI;

	@Autowired
	@Qualifier("com.jy.modules.cims.component.sysAssist.BatchService")
	public BatchService batchService;
	
	/** 
	 * 
	 * @Description    结算申请处理
	 * void  
	 * @throws
	 * @author zhangmi
	 * @date 2016-4-15
	 */
	public void settleApply(List<CreditDetailDto> listCreditDetail) throws Exception{
		//根据交易流水号拆分债权list
		HashMap<String, List<CreditDetailDto>> requestMap = new HashMap<String, List<CreditDetailDto>>();
		for (CreditDetailDto creditDetailDto : listCreditDetail) {
			String dealCode = creditDetailDto.getDealCode();
			if(SimpleStringUtils.hasText(dealCode)){
				if(requestMap.containsKey(dealCode)){
					requestMap.get(dealCode).add(creditDetailDto);
				}else{
					requestMap.put(dealCode, new ArrayList<CreditDetailDto>());
					requestMap.get(dealCode).add(creditDetailDto);
				}
			}
		}
		//迭代map进行发送
		Iterator<String> keys = requestMap.keySet().iterator(); 
		while(keys.hasNext()) { 
		   String dealCode = (String) keys.next(); //交易流水号
		   String applyCode = settleUtilsService.autoMakeSettleApplyCode(dealCode);//结算编号
		   List<CreditDetailDto> requestList = requestMap.get(dealCode); //债权明细list
		   //验证是否发送
		   CostAffiliationResultDto costAffiliationResultDto = settleUtilsService.checkCostByDealCode(dealCode,"01");
		   for (CreditDetailDto creditDetailDto : requestList) {
			   if(!costAffiliationResultDto.isServiceFee()){
				   creditDetailDto.setServiceCharge(new BigDecimal(0));
			   }
			   if(!costAffiliationResultDto.isMarginFee()){
				   creditDetailDto.setCautionMoney(new BigDecimal(0));
			   }
			   if(!costAffiliationResultDto.isGuaranteeFee()){
				   creditDetailDto.setGuaranteeFee(new BigDecimal(0));
			   }
		   }
		   //参数组装
		   PublicSettleParamDto publicSettleParamDto = new PublicSettleParamDto();
		   publicSettleParamDto.setCreditDetailList(requestList);
		   publicSettleParamDto.setApplyCode(applyCode);
		   publicSettleParamDto.setDealCode(dealCode);
		   publicSettleParamDto.setCCode(requestList.get(0).getCooperorgCode());
		   publicSettleParamDto.setApplyName(sessionAPI.getCurrentUserInfo().getUserName());
		   //发送结算申请
		   doSettleApply(publicSettleParamDto);		
		} 
		
		
		
		
	}
	
	/**
	 * 
	 * @Description 
	 * @param publicSettleParamDto   
	 * void  
	 * @throws Exception 
	 * @throws
	 * @author zhangmi
	 * @date 2016-4-18
	 */
	public void doSettleApply(PublicSettleParamDto publicSettleParamDto) throws Exception{
		
		StringBuffer resultMsg = new StringBuffer();
		try {
			List<CreditDetailDto> responseList = publicSettleParamDto.getCreditDetailList();
			String dealCode = publicSettleParamDto.getDealCode();
			String applyCode = publicSettleParamDto.getApplyCode();
			logger.info("交易流水号："+dealCode+"，结算申请编号："+applyCode+",结算申请开始发送！");
			PublicSettleResultDto resultDto=  iCInteract.sendSettleApply(publicSettleParamDto);
			if(resultDto.isSuccess()){
				//修改数据库状态
				TCMmCreditDealDetailDTO dto = null;
				for (CreditDetailDto creditDetailDto : responseList) {
					dto = new TCMmCreditDealDetailDTO();
					dto.setSettleApplyId(applyCode);
					dto.setTransferId(creditDetailDto.getTransferId());
					dto.setCostState(CimsConstant.COST_STATUS_SQ);
					dto.setDealStreamCode(dealCode);
					creditDealDetailDao.updateCreditDealDetailSettleApply(SearchParamUtil.getSearchParam(dto));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMsg.append(e.getMessage());
			logger.error("交易流水号："+publicSettleParamDto.getDealCode()+",结算编号为："+publicSettleParamDto.getApplyCode()+"数据发送结算申请失败！");
			throw new Exception("交易流水号："+publicSettleParamDto.getDealCode()+",结算编号为："+publicSettleParamDto.getApplyCode()+"数据发送结算申请失败！");
		}
	}
	
	/**
	 * 
	 * @Description    结算赎回申请处理
	 * void  
	 * @throws
	 * @author zhangmi
	 * @date 2016-4-15
	 */
	public void doSettleRedeem(){
		
	}
	
	/**
	 * 更新流水表的结算状态
	 * @Description    
	 * void  
	 * @throws
	 * @author zhangmi
	 * @date 2016-7-8
	 */
	public void updateCooperorgDealCostState(){
		Map<String, List<DealDto>> map = new HashMap<String, List<DealDto>>();
		Map<String, List<DealDto>> loanMap = new HashMap<String, List<DealDto>>();
		List<DealDto> list = creditDealDetailDao.searchCooperorgDealCostState(SearchParamUtil.getSearchParam());
		if(CollectionsUtils.isNotEmpty(list)){
			for (DealDto dealDto : list) {
				
				String dealType = dealDto.getDealType().trim();
				if("03".equals(dealType)){
					this.getCalcCostStatusMap(loanMap, dealDto);
				}else{
					this.getCalcCostStatusMap(map, dealDto);
				}
				
			}
		}
		if(map.containsKey(CimsConstant.DEAL_COST_STATUS_QBJS)){//全部结算
			Map<Object, Object> paramsMap = new HashMap<Object, Object>();
			paramsMap.put("status", CimsConstant.DEAL_COST_STATUS_QBJS);
			batchService.batchInvoke(SettleBalanceService.class, "updateCostStateByBatch", map.get(CimsConstant.DEAL_COST_STATUS_QBJS), paramsMap, 500);
		
		}
		if(map.containsKey(CimsConstant.DEAL_COST_STATUS_BFJS)){//部分结算
			Map<Object, Object> paramsMap = new HashMap<Object, Object>();
			paramsMap.put("status", CimsConstant.DEAL_COST_STATUS_BFJS);
			batchService.batchInvoke(SettleBalanceService.class, "updateCostStateByBatch", map.get(CimsConstant.DEAL_COST_STATUS_BFJS), paramsMap, 500);
		}
		if(map.containsKey(CimsConstant.DEAL_COST_STATUS_DJS)){//待结算
			Map<Object, Object> paramsMap = new HashMap<Object, Object>();
			paramsMap.put("status", CimsConstant.DEAL_COST_STATUS_DJS);
			batchService.batchInvoke(SettleBalanceService.class, "updateCostStateByBatch", map.get(CimsConstant.DEAL_COST_STATUS_DJS), paramsMap, 500);
		}
	}
	
	/**
	 * 算流水结算状态
	 * @author zhangmi
	 * @date  2016年9月9日
	 * @param map
	 * @param dealDto
	 * @return
	 */
	public Map<String, List<DealDto>> getCalcCostStatusMap(Map<String, List<DealDto>> map,DealDto dealDto){
		String costState = dealDto.getCostState().trim();
		if(SimpleStringUtils.hasText(costState)){
			if(costState.indexOf(",")>-1){//两个以上的状态
				if(costState.indexOf(CimsConstant.COST_STATUS_YJ)>-1){//包含已结算的
					if(map.containsKey(CimsConstant.DEAL_COST_STATUS_BFJS)){ //修改状态：部分结算
						map.get(CimsConstant.DEAL_COST_STATUS_BFJS).add(dealDto);
					}else{
						map.put(CimsConstant.DEAL_COST_STATUS_BFJS, new ArrayList<DealDto>());
						map.get(CimsConstant.DEAL_COST_STATUS_BFJS).add(dealDto);
					}
				}else{//结算中,驳回
					if(map.containsKey(CimsConstant.DEAL_COST_STATUS_DJS)){ //修改状态：待结算
						map.get(CimsConstant.DEAL_COST_STATUS_DJS).add(dealDto);
					}else{
						map.put(CimsConstant.DEAL_COST_STATUS_DJS, new ArrayList<DealDto>());
						map.get(CimsConstant.DEAL_COST_STATUS_DJS).add(dealDto);
					}
				}
			}else{
				if(CimsConstant.COST_STATUS_SQ.equals(costState)
						||CimsConstant.COST_STATUS_BH.equals(costState)){ //全部为申请结算，或者全部驳回
					if(map.containsKey(CimsConstant.DEAL_COST_STATUS_DJS)){ //修改状态：待结算
						map.get(CimsConstant.DEAL_COST_STATUS_DJS).add(dealDto);
					}else{
						map.put(CimsConstant.DEAL_COST_STATUS_DJS, new ArrayList<DealDto>());
						map.get(CimsConstant.DEAL_COST_STATUS_DJS).add(dealDto);
					}
				}else if(CimsConstant.COST_STATUS_YJ.equals(costState)){//全部为已结算
					if(map.containsKey(CimsConstant.DEAL_COST_STATUS_QBJS)){ //修改状态：全部结算
						map.get(CimsConstant.DEAL_COST_STATUS_QBJS).add(dealDto);
					}else{
						map.put(CimsConstant.DEAL_COST_STATUS_QBJS, new ArrayList<DealDto>());
						map.get(CimsConstant.DEAL_COST_STATUS_QBJS).add(dealDto);
					}
				}
			}
		}else{
			logger.info("更新流水表结算状态异常：修改状态为空!"+costState);
		}
		return map;
	}
	
	
	/**
	 * 
	 * @author zhangmi
	 * @date  2016年9月9日
	 * @param map
	 */
	public void updateCooperorgDealCostStateAll(Map<String, List<DealDto>> map){
		
	}
	
	/**
	 * 
	 * @author zhangmi
	 * @date  2016年11月17日
	 * @param list
	 * @param paramsMap
	 */
	public void updateCostStateByBatch(List<DealDto> list,Map<Object, Object> paramsMap){
		AssistDealDto  dto = new AssistDealDto();
		dto.setCostState(paramsMap.get("status").toString());
		dto.setListDeal(list);
		creditDealDetailDao.updateCooperorgDealCostState(SearchParamUtil.getSearchParam(dto));
	}
}
